﻿using HZY.Framework.DependencyInjection;
using MiniExcelLibs;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OscarClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

namespace Apple.SprayingProcessSystem
{
    public partial class PageLogManage : UIPage, ISingletonSelfDependency
    {
        public PageLogManage()
        {
            InitializeComponent();
            InitCbData();
        }

        /// <summary>
        /// 获取Logs目录下的日期文件夹加载到Combobox
        /// </summary>
        private void InitCbData()
        {
            string path = Path.Combine(Application.StartupPath, "Logs");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string[] dirNames = Directory.GetDirectories(path);
            dirNames.ForEach(x =>
            {
                this.cb_Date.Items.Add(Path.GetFileName(x));
            });

        }

        /// <summary>
        /// 获取日期文件夹下的Info、Error、Warning等文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cb_Date_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_Date.SelectedItem == null)
            {
                UIMessageTip.ShowWarning("请选择日期!");
                return;
            }
            string path = Path.Combine(Application.StartupPath, "logs", cb_Date.SelectedItem.ToString());

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string[] dirNames = Directory.GetDirectories(path);
            cb_LogLev.Items.Clear();

            dirNames.ForEach(x =>
            {
                cb_LogLev.Items.Add(Path.GetFileName(x));
            });
        }

        /// <summary>
        /// 根据日期和等级加载日志文件到ListBox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cb_LogLev_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_Date.SelectedItem == null)
            {
                UIMessageTip.ShowWarning("请选择日期!");
                return;
            }

            if (cb_LogLev.SelectedItem == null)
            {
                UIMessageTip.ShowWarning("请选择日志等级!");
                return;
            }

            this.lb_Files.Items.Clear();
            string path = Path.Combine(Application.StartupPath, "Logs", cb_Date.SelectedItem.ToString(), cb_LogLev.SelectedItem.ToString());

            string[] fileNames = Directory.GetFiles(path, "*.log");

            fileNames.OrderBy(x => x).ToList().ForEach(x =>
            {
                lb_Files.Items.Add(Path.GetFileName(x));
            });

        }

        /// <summary>
        /// 选择日志文件显示在文本框上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void lb_Files_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_Date.SelectedItem == null)
            {
                UIMessageTip.ShowWarning("请选择日期!");
                return;
            }

            if (cb_LogLev.SelectedItem == null)
            {
                UIMessageTip.ShowWarning("请选择日志等级!");
                return;
            }

            if (lb_Files.SelectedItem == null)
            {
                UIMessageTip.ShowWarning("请选择日志文件!");
                return;
            }

            try
            {
                string path = Path.Combine(Application.StartupPath, "Logs", cb_Date.SelectedItem.ToString(), cb_LogLev.SelectedItem.ToString(), lb_Files.SelectedItem.ToString());

                this.txt_ShowLog.Text = string.Empty;

                string content = string.Empty;

                using (StreamReader sr = new StreamReader(path))
                {
                    content = await sr.ReadToEndAsync();
                }

                this.txt_ShowLog.Text = content;
            }
            catch (Exception ex)
            {
                LogExtension.ShowMessage(ex.Message, LogLevel.Error);
            }
        }

        /// <summary>
        /// 打开日志目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OpenDire_Click(object sender, EventArgs e)
        {
            string logPath = Path.Combine(Application.StartupPath, "Logs");

            ProcessStartInfo startInfo = new ProcessStartInfo()
            {
                FileName = logPath,
                UseShellExecute = true,  // 使用操作系统shell启动进程
            };

            Process process = new Process
            {
                StartInfo = startInfo
            };

            process.Start();

        }

        /// <summary>
        /// 显示到表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ShowToDgv_Click(object sender, EventArgs e)
        {
            if (this.txt_ShowLog.Text.Length == 0)
            {
                UIMessageTip.ShowWarning("请选择日志文件");
                return;
            }

            string[] lines = txt_ShowLog.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            DataTable dt = new DataTable();
            dt.Columns.Add("时间");
            dt.Columns.Add("日志等级");
            dt.Columns.Add("日志来源");
            dt.Columns.Add("日志内容");

            lines.ToList().ForEach(line =>
            {
                string[] items = line.Split(new string[] { "|" }, StringSplitOptions.None);

                if (items.Length == 4)
                {
                    DataRow dr = dt.NewRow();
                    dr["时间"] = items[0];
                    dr["日志等级"] = items[1];
                    dr["日志来源"] = items[2];
                    dr["日志内容"] = items[3];
                    dt.Rows.Add(dr);
                }
            });

            dgv_ShowLog.DataSource = dt;
        }

        /// <summary>
        /// 日志导出txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ShowToTXT_Click(object sender, EventArgs e)
        {
            if (this.txt_ShowLog.Text == string.Empty)
            {
                UIMessageTip.ShowWarning("请选择日志文件");
                return;
            }

            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                try
                {
                    saveFileDialog.Filter = "文本文件|*.txt";
                    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        using (StreamWriter sw = new StreamWriter(saveFileDialog.FileName))
                        {
                            await sw.WriteAsync(this.txt_ShowLog.Text);
                        }

                        LogExtension.ShowMessage("日志导出成功!", LogLevel.Information);

                        ProcessStartInfo processStart = new ProcessStartInfo
                        {
                            FileName = saveFileDialog.FileName,
                            UseShellExecute = true,
                        };

                        Process process = new()
                        {
                            StartInfo = processStart
                        };

                        process.Start();
                    }
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowError(ex.Message);
                    LogExtension.ShowMessage(ex.Message, LogLevel.Error);
                }

            }
        }

        /// <summary>
        /// 日志导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ExportExcel_Click(object sender, EventArgs e)
        {
            if (this.dgv_ShowLog.DataSource == null)
            {
                UIMessageTip.ShowWarning("请先选择日志文件");
                return;
            }

            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                try
                {
                    sfd.Filter = "Excel文件|*.xlsx";
                    sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        DataTable dt = this.dgv_ShowLog.DataSource as DataTable;

                        await MiniExcel.SaveAsAsync(sfd.FileName, dt);
                        LogExtension.ShowMessage("日志导出成功!", LogLevel.Information);

                        ProcessStartInfo processStart = new ProcessStartInfo()
                        {
                            FileName = sfd.FileName,
                            UseShellExecute = true,
                        };

                        Process process = new Process
                        {
                            StartInfo=processStart
                        };

                        process.Start();
                    }
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowError(ex.Message);
                    LogExtension.ShowMessage(ex.Message, LogLevel.Error);
                }

            }

        }

        #region 窗体切换卡顿处理
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams paras = base.CreateParams;
                paras.ExStyle |= 0x02000000;
                return paras;
            }
        }
        #endregion
    }
}
